<template>
	<view class="store-list">
		<!-- 遍历商店列表 -->
		<view v-for="(store, storeIndex) in stores" :key="storeIndex" class="store">
			<view class="store-header">
				<!-- 商店复选框 -->
				<checkbox class="store-selector" @click="onSelectStore(storeIndex,store.sellerID)"
					:checked="store.selected" color="#ffffff" activeBackgroundColor="#FFCC33"
					activeBorderColor="#ffffff"></checkbox>
				<!-- 商店名称 -->
				<text class="store-name">{{ store.sellerName }}</text>
				<!-- 导航图标 -->
				<uni-icons type="forward" size="18" @click="goToSeller(store.sellerID)"></uni-icons>
			</view>
			<!-- 遍历商店中的商品列表 -->
			<view v-for="(item, itemIndex) in store.cartItems" :key="itemIndex" class="item-row">
				<!-- 商品信息 -->
				<view class="item-info">
					<!-- 商品复选框 -->
					<checkbox class="item-selector" @click="onSelectItem(storeIndex, itemIndex,item.goodsID)"
						:checked="item.selected" color="#ffffff" activeBackgroundColor="#FFCC33"
						activeBorderColor="#ffffff"></checkbox>
					<!-- 商品图片 -->
					<image class="item-image" :src="item.image"></image>
					<!-- 商品名称、价格和数量 -->
					<view class="item-details">
						<!-- 商品名称 -->
						<text class="item-name">{{ item.goodsName }}</text>
						<!-- 价格和数量容器 -->
						<view class="item-quantity-container">
							<!-- 商品价格 -->
							<text class="item-price">￥{{ item.price * item.num | formatPrice }}</text>
							<!-- 商品数量控制 -->
							<view class="item-quantity">
								<button class="decrease-button"
									@click="decreaseQuantity(storeIndex, itemIndex)">-</button>
								<text class="quantity-text">{{ item.num }}</text>
								<button class="increase-button"
									@click="increaseQuantity(storeIndex, itemIndex)">+</button>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>

	<!-- 结算模块 -->
	<view class="checkout-module" id="checkoutModule">

		<checkbox class="checkout-selector" @click="toggleSelectAll" :checked="isAllSelected" color="#ffffff"
			activeBackgroundColor="#FFCC33" activeBorderColor="#ffffff">全选</checkbox>

		<!-- 合计价格 -->
		<text class="total-price">合计:<text class="total-price-color">￥{{ totalPrice | formatPrice }}</text></text>
		<button @click="checkout">结算</button>
		<!-- 其他结算相关的信息和按钮 -->
	</view>

	<view class="back-to-top" v-show="isVisible" @click="scrollToTop">
		<uni-icons type="up"></uni-icons>
		<span>顶部</span>
	</view>

</template>

<script>
	import axios from 'axios';
	import service from '../../utils/request.js';
	export default {
		data() {
			return {
				userID: null,
				isVisible: false,
				isAllSelected: false,
				receiverName: '',
				receiverPhone: '',
				receiverAddress: '',
				stores: [{
					// name: '奥利奥宠物商店',
					selected: false,
					cartItems: []
				}, ],
			};
		},
		computed: {
			totalPrice() {
				// 计算所有选中商品的总价
				let total = 0;
				this.stores.forEach(store => {
					store.cartItems.forEach(item => {
						if (item.selected) {
							total += item.price * item.num;
						}
					});
				});
				return total;
			},
		},

		methods: {
			goToSeller(sellerID) {
				uni.setStorageSync('sellerID', sellerID)
				uni.navigateTo({
					url: '/pages/seller/seller?sellerID=${sellerID}'
				});
			},
			async getCartData() {
				try {
					this.userID = localStorage.getItem("userID");
					// 获取商品及其商家信息
					const response = await service.get('/cart/goodsAndSellers/' + this.userID);
					console.log('商品信息:', response);
					const storesInfo = response.sellerList;
					const cartItems = response.goodsList;
					// 整合数据到 stores 数组中
					const storesMap = new Map();
					storesInfo.forEach(store => {
						if (!storesMap.has(store.sellerID)) {
							storesMap.set(store.sellerID, {
								...store,
								selected: store.selected,
								cartItems: []
							});
						}
					});

					cartItems.forEach(item => {
						const store = storesMap.get(item.sellerID);
						if (store) {
							store.cartItems.push({
								...item,
								selected: item.selected // 确保从后端获取selected状态
							});
						}
					});

					this.stores = Array.from(storesMap.values());

					console.log('整合后的数据111:', response);
				} catch (error) {
					console.error('获取数据失败:', error);
				}
			},

			resetSelections() {
				// 重置全选按钮状态
				this.isAllSelected = false;

				// 遍历所有商店，重置商店和商品的选中状态
				this.stores.forEach(store => {
					store.selected = false;
					store.cartItems.forEach(item => {
						item.selected = false;
					});
				});
			},
			scrollToTop() {
				window.scrollTo({
					top: 0,
					behavior: 'smooth',
				});
			},
			onScroll() {
				this.isVisible = window.scrollY > 100;
			},
			async updateSelectionStatus(data) {
				try {
					const response = await service.post('/cart/updateSelectionStatus', {
						userID: this.userID,
						...data
					});
					console.log('状态更新成功:', response);
				} catch (error) {
					console.error('状态更新失败:', error);
				}
			},
			async toggleSelectAll() {
				// 切换所有商品的选中状态
				this.isAllSelected = !this.isAllSelected;
				let updatePromises = [];

				this.stores.forEach(store => {
					store.selected = this.isAllSelected;
					store.cartItems.forEach(item => {
						item.selected = this.isAllSelected;
						// 为每个商品创建一个更新状态的请求
						updatePromises.push(this.updateSelectionStatus({
							userID: this.userID,
							sellerID: store.sellerID,
							goodsID: item.goodsID,
							selected: this.isAllSelected
						}));
					});
				});

				// 等待所有更新操作完成
				try {
					await Promise.all(updatePromises);
					console.log('所有商品状态更新成功');
				} catch (error) {
					console.error('商品状态更新失败:', error);
				}
			},
			async deselectAllItems() {
				this.isAllSelected = false;
				let updatePromises = [];

				this.stores.forEach(store => {
					store.selected = this.isAllSelected;
					store.cartItems.forEach(item => {
						item.selected = this.isAllSelected;
						// 为每个商品创建一个更新状态的请求
						updatePromises.push(this.updateSelectionStatus({
							userID: this.userID,
							sellerID: store.sellerID,
							goodsID: item.goodsID,
							selected: this.isAllSelected
						}));
					});
				});

				// 等待所有更新操作完成
				try {
					await Promise.all(updatePromises);
					console.log('所有商品状态更新成功');
				} catch (error) {
					console.error('商品状态更新失败:', error);
				}
			},
			onSelectStore(storeIndex, sellerID) {
				const store = this.stores[storeIndex];
				store.selected = !store.selected; // 切换选中状态
				// 同步商品的选中状态
				store.cartItems.forEach((item) => {
					item.selected = store.selected;
				});

				this.updateSelectionStatus({
					sellerID: sellerID,
					selected: store.selected
				});

				// 重新计算全选按钮的状态
				this.updateSelectAllStatus();



			},
			onSelectItem(storeIndex, itemIndex, goodsID) {
				const store = this.stores[storeIndex];
				const item = store.cartItems[itemIndex];
				item.selected = !item.selected; // 切换选中状态
				// 如果当前是全选状态，需要重新计算
				this.updateSelectionStatus({
					goodsID: goodsID,
					selected: item.selected
				});
				this.updateSelectAllStatus();


			},
			updateSelectAllStatus() {
				// 检查是否有任何一个商品或商店未选中，如果是，则全选状态应该取消
				this.isAllSelected = this.stores.every(store => {
					const allItemsSelected = store.cartItems.every(item => item.selected);
					store.selected = allItemsSelected; // 更新店家的选中状态
					return allItemsSelected;
				});
			},
			increaseQuantity(storeIndex, itemIndex) {
				const item = this.stores[storeIndex].cartItems[itemIndex];
				if (item.num < 9) { // 假设最多只能加到10个
					item.num++;
				}

			},
			decreaseQuantity(storeIndex, itemIndex) {
				const item = this.stores[storeIndex].cartItems[itemIndex];
				if (item.num > 1) {
					item.num--;
				}

			},
			async checkout() {
				console.log('结算购物车中的商品');
				uni.navigateTo({
					url: '/pages/order-confirm/order-confirm'
				});
			},

		},
		mounted() {
			window.addEventListener('scroll', this.onScroll);
			this.updateSelectAllStatus();

		},

		onShow() {
			this.getCartData();
			this.updateSelectAllStatus();
		},
		created() {
			this.resetSelections();
		},
		beforeDestroy() {
			window.removeEventListener('scroll', this.onScroll);
		},
		filters: {
			formatPrice(value) {
				return value.toFixed(2);
			},
		},
	};
</script>

<style lang="scss" scoped>
	@use "cart";
</style>